<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item :label="$t('rule.Stichwort')" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            :placeholder="$t('rule.Regelname')"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button v-throttle="handleQuery" type="primary"
            ><el-icon style="margin-right: 5px; font-size: 18px">
              <Search /> </el-icon
            >{{ $t("rule.Suche") }}</el-button
          >
          <el-button v-throttle="resetQuery" type="">
            <el-icon style="margin-right: 5px; font-size: 18px">
              <Refresh /> </el-icon
            >{{ $t("rule.Zurücksetzen") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 编辑任务信息 -->
    <el-dialog
      v-model="dialog.visible"
      :title="$t('rule.' + dialog.title)"
      width="900px"
      append-to-body
      @close="closeDialog"
    >
      <el-form>
        <el-form-item>
          <el-table
            :data="ruleListOf"
            highlight-current-row
            :tree-props="{
              children: 'children',
              hasChildren: 'hasChildren',
            }"
            row-key="id"
            default-expand-all
            border
            size="small"
          >
            <el-table-column
              :label="$t('rule.Regelname')"
              align="left"
              prop="name"
            />
            <el-table-column
              :label="$t('rule.Typ')"
              align="center"
              prop="type"
              width="80"
            >
              <template #default="scope">
                <el-tag
                  v-if="scope.row.type === RuleTypeEnum.CALLED"
                  type="warning"
                  >{{ $t("rule.anrufen") }}</el-tag
                >
                <el-tag
                  v-if="scope.row.type === RuleTypeEnum.BRANCH"
                  type="success"
                  >{{ $t("rule.Zweig") }}</el-tag
                >
                <el-tag
                  v-if="scope.row.type === RuleTypeEnum.RULE"
                  type="danger"
                  >{{ $t("rule.Regel") }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('rule.Bruch')"
              align="center"
              width="150"
              prop="grades"
            />
            <el-table-column
              :label="$t('rule.sortieren')"
              align="center"
              width="150"
              prop="sort"
            />
            <el-table-column
              fixed="right"
              align="center"
              :label="$t('rule.Betrieb')"
              width="220"
            >
              <template #default="scope">
                <el-button
                  v-if="
                    scope.row.type == 'CALLED' || scope.row.type == 'BRANCH'
                  "
                  v-hasPerm="['courseinfo:rule:add']"
                  v-throttle="
                    () =>
                      openEditDialog(scope.row.id, undefined, scope.row.type)
                  "
                  type="primary"
                  link
                  size="small"
                >
                  <i-ep-plus />{{ $t("rule.Hinzufügen") }}
                </el-button>
                <el-button
                  v-hasPerm="['courseinfo:rule:edit']"
                  v-throttle="() => openEditDialog(undefined, scope.row.id)"
                  type="primary"
                  link
                  size="small"
                >
                  <i-ep-edit />{{ $t("rule.bearbeiten") }}
                </el-button>
                <el-button
                  v-if="scope.row.type != 'CALLED'"
                  v-hasPerm="['courseinfo:rule:delete']"
                  v-throttle="() => handleRuleDelete(scope.row.id)"
                  type="danger"
                  link
                  size="small"
                  ><i-ep-delete />
                  {{ $t("rule.löschen") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary">确 认</el-button> -->
          <el-button @click="closeDialog">{{ $t("rule.zurück") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['courseinfo:rule:add']"
              v-throttle="openAddDialog"
              type="success"
              ><i-ep-plus />{{ $t("rule.Hinzufügen") }}</el-button
            >
            <el-button
              v-hasPerm="['courseinfo:rule:delete']"
              v-throttle="handleDelete"
              type="danger"
              :disabled="ids.length === 0"
              ><i-ep-delete />{{ $t("rule.löschen") }}</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="ruleList"
        :empty-text="$t('rule.DerzeitRegelinformationen')"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          key="id"
          :label="$t('rule.Zahl')"
          align="center"
          prop="id"
          width="100"
        />
        <el-table-column
          key="name"
          :label="$t('rule.Regelname')"
          align="center"
          prop="name"
        />
        <el-table-column
          :label="$t('rule.Benutzererstellen')"
          width="120"
          align="center"
          prop="nickname"
        />

        <el-table-column
          :label="$t('rule.Erstellungszeit')"
          align="center"
          prop="createTime"
        />

        <el-table-column
          :label="$t('rule.Aktualisierungszeit')"
          align="center"
          prop="updateTime"
        />
        <el-table-column :label="$t('rule.Betrieb')" fixed="right" width="220">
          <template #default="scope">
            <el-button
              v-throttle="() => editRule(scope.row.id)"
              type="primary"
              link
              size="small"
              ><i-ep-edit />{{ $t("rule.Prüfung") }}</el-button
            >
            <el-button
              v-throttle="() => handleDelete(scope.row.id)"
              type="danger"
              link
              size="small"
              ><i-ep-delete />{{ $t("rule.löschen") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 编辑具体的规则的dialog -->
    <el-dialog
      v-model="editRuleDialog.visible"
      :title="$t('rule.' + editRuleDialog.title)"
      destroy-on-close
      append-to-body
      width="750px"
      @close="closeEditRuleDialog"
    >
      <el-form ref="editFormRef" :model="editRuleFormData" :rules="editRules">
        <el-form-item
          v-if="editRuleFormData.type != 'CALLED'"
          :label="$t('rule.ÜbergeordneteRegel')"
          prop="parentId"
        >
          <el-tree-select
            v-model="editRuleFormData.parentId"
            :placeholder="$t('rule.ÜberlegeneRegelnauswählen')"
            :data="ruleOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item :label="$t('rule.Regelname')" prop="name">
          <el-input
            v-model="editRuleFormData.name"
            :placeholder="$t('rule.BitteRegelnamen')"
          />
        </el-form-item>

        <el-form-item
          v-if="editRuleFormData.type != 'CALLED'"
          :label="$t('rule.Regeltyp')"
          prop="type"
        >
          <el-radio-group
            v-model="editRuleFormData.type"
            @change="onRuleTypeChange"
          >
            <el-radio label="BRANCH">{{ $t("rule.Zweig") }}</el-radio>
            <el-radio label="RULE">{{ $t("rule.Regel") }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="editRuleFormData.type == 'RULE'"
          :label="$t('rule.Leistung')"
          prop="grades"
        >
          <el-input
            v-model="editRuleFormData.grades"
            :placeholder="$t('rule.BitteRegelwert')"
          />
        </el-form-item>

        <el-form-item
          v-if="editRuleFormData.type != 'CALLED'"
          :label="$t('rule.sortieren')"
          prop="sort"
        >
          <el-input-number
            v-model="editRuleFormData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-throttle="submitEditForm" type="primary">{{
            $t("rule.bestätigen")
          }}</el-button>
          <el-button @click="closeEditRuleDialog">{{
            $t("rule.Abbrechen")
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增规则模板的dialog -->
    <el-dialog
      v-model="addDialog.visible"
      :title="$t('rule.' + addDialog.title)"
      destroy-on-close
      append-to-body
      width="750px"
      @close="closeAddDialog"
    >
      <local-loading :loading="addTemplateLoading"></local-loading>
      <el-form
        v-show="!addTemplateLoading"
        ref="addFormRef"
        :model="addFormData"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item :label="$t('rule.Regelvorlage')">
          <el-radio-group v-model="templateType" @change="onTemplateChange">
            <el-radio
              v-for="dict in course_rule_template"
              :key="dict.value"
              :label="dict.value"
              >{{
                translateTagDictI18n("course_rule_template", dict.label)
              }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="templateType == '3'"
          :label="$t('rule.Regelgesamtname')"
          prop="name"
        >
          <el-input
            v-model="addFormData.name"
            :placeholder="$t('rule.BitteGesamtnamen')"
          />
        </el-form-item>

        <el-form-item
          v-if="templateType == '2'"
          :label="$t('rule.Vorlagenkurs')"
          prop="courseId"
        >
          <el-select
            v-model="addFormData.courseId"
            :placeholder="$t('rule.BitteSieKurs')"
            @change="onCourseChange"
          >
            <el-option
              v-for="item in courseOptions"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <div style="width: 100%; padding: 0 20px">
          <el-table
            v-if="templateType != '3'"
            :data="templateRules"
            :loading="tableRuleLoading"
            :empty-text="$t('rule.DerzeitVorlagendaten')"
            style="width: 100%"
          >
            <el-table-column
              :data="templateData"
              prop="name"
              :label="$t('rule.Vorlagenname')"
            />
            <el-table-column
              fixed="right"
              :label="$t('rule.Betrieb')"
              width="120"
            >
              <template #default="scope">
                <el-button
                  v-throttle="() => showTemplateRule(scope.row.id)"
                  link
                  type="primary"
                  size="small"
                  >{{ $t("rule.Prüfung") }}</el-button
                >
                <el-button
                  v-throttle="() => selectTemplateRule(scope.row.id)"
                  link
                  type="primary"
                  size="small"
                  >{{ $t("rule.Wahl") }}</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="templateType == '3'"
            type="primary"
            @click="submitAddForm"
            >{{ $t("rule.bestätigen") }}</el-button
          >
          <el-button @click="closeAddDialog">{{
            $t("rule.Abbrechen")
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑任务信息 -->
    <el-dialog
      v-model="showTemplateDialog.visible"
      :title="$t('rule.' + showTemplateDialog.title)"
      width="900px"
      append-to-body
      @close="showTemplateDialog.visible = false"
    >
      <el-form>
        <el-form-item>
          <el-table
            :data="templateRuleFormData"
            highlight-current-row
            :tree-props="{
              children: 'children',
              hasChildren: 'hasChildren',
            }"
            row-key="id"
            default-expand-all
            border
            size="small"
          >
            <el-table-column
              :label="$t('rule.Regelname')"
              align="left"
              prop="name"
            />
            <el-table-column
              :label="$t('rule.Typ')"
              align="center"
              prop="type"
              width="80"
            >
              <template #default="scope">
                <el-tag
                  v-if="scope.row.type === RuleTypeEnum.CALLED"
                  type="warning"
                  >{{ $t("rule.anrufen") }}</el-tag
                >
                <el-tag
                  v-if="scope.row.type === RuleTypeEnum.BRANCH"
                  type="success"
                  >{{ $t("rule.Zweig") }}</el-tag
                >
                <el-tag
                  v-if="scope.row.type === RuleTypeEnum.RULE"
                  type="danger"
                  >{{ $t("rule.Regel") }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('rule.Bruch')"
              align="center"
              width="150"
              prop="grades"
            />
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showTemplateDialog.visible = false">{{
            $t("rule.zurück")
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Rule",
  inheritAttrs: false,
});
import {
  getRuleForm,
  getRulePage,
  listRuleOptions,
  ruleListInfo,
  updateRule,
  addRule,
  deleteRule,
  getTemplateRules,
  saveRuleByTemplate,
  deleteRules,
  getCourseOptions,
  getRuleByCourseId,
  addCustomRule,
} from "@/api/rule";
import { RulePageVO, RuleQuery, RuleForm, AddRuleForm } from "@/api/rule/types";
import { translateTagDictI18n } from "@/utils/i18n";
import { RuleTypeEnum } from "@/enums/RuleTypeEnum";
import { useAppStore } from "@/store/modules/app";
import { useCourseStore } from "@/store/modules/course";
const courseStore = useCourseStore();
const courseId = ref();

// 汉堡
const appStore = useAppStore();
// 字典
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { course_rule_template } = proxy?.useDict("course_rule_template");
const ruleListOf = ref<RuleForm[]>();
const templateRuleFormData = ref<RuleForm[]>();
const ruleOptions = ref<OptionType[]>([]);
const courseOptions = ref<OptionType[]>([]);
const editFormRef = ref(ElForm);
const addFormRef = ref(ElForm);
const ruleIdCache = ref(0);
const total = ref(0);
const ids = ref([]);
const templateType = ref("1");
// 创建弹窗组件
const addDialog = reactive<DialogOption>({
  visible: false,
});
// 创建弹窗组件
const dialog = reactive<DialogOption>({
  visible: false,
});
// 创建弹窗组件
const editRuleDialog = reactive<DialogOption>({
  visible: false,
});
const showTemplateDialog = reactive<DialogOption>({
  visible: false,
});
const queryParams = reactive<RuleQuery>({
  pageNum: 1,
  pageSize: 10,
});
const editRuleFormData = reactive<RuleForm>({
  parentId: 0,
  sort: 1,
  type: RuleTypeEnum.BRANCH,
  value: undefined,
  children: [],
});
const addFormData = reactive<AddRuleForm>({
  type: 1,
});
const ruleCacheData = reactive<{
  type: string;
  grades: number | undefined;
}>({
  type: "",
  grades: undefined,
});
const editRules = reactive({
  parentId: [{ required: true, message: "请选择顶级规则", trigger: "blur" }],
  name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择规则类型", trigger: "blur" }],
  grades: [{ required: true, message: "请填写规则成绩", trigger: "blur" }],
});
const addRules = reactive({
  courseId: [{ required: true, message: "请选择模板课程", trigger: "blur" }],
  name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
});
const ruleList = ref<RulePageVO[]>();
const templateRules = ref<RulePageVO[]>();
const templateData = ref<RulePageVO[]>();
const queryFormRef = ref(ElForm); // 查询表单
const loading = ref(false);
const tableRuleLoading = ref(false);
const addTemplateLoading = ref(false);

function editRule(ruleId: number) {
  ruleIdCache.value = ruleId;

  openDialog();
  ruleListInfo(ruleId).then(({ data }) => {
    ruleListOf.value = data;
  });
}
// 查询
function handleQuery() {
  loading.value = true;
  getRulePage(queryParams, courseId.value)
    .then(({ data }) => {
      ruleList.value = data.list;

      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 查询
function showTemplateRule(ruleId: number) {
  showTemplateDialog.visible = true;
  showTemplateDialog.title = "查看规则模板示例";
  ruleListInfo(ruleId).then(({ data }) => {
    templateRuleFormData.value = data;
    // Object.assign(templateRuleFormData, data);
  });
}
// 查询
function selectTemplateRule(ruleId: number) {
  ElMessageBox.confirm("确认选择此模板吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    addTemplateLoading.value = true;
    saveRuleByTemplate(ruleId, courseId.value)
      .then(() => {
        addDialog.visible = false;
        ElMessage.success("添加成功");
        handleQuery();
      })
      .catch(() => {
        ElMessage.error("添加失败");
      })
      .finally(() => {
        addTemplateLoading.value = false;
      });
  });
}
// 重置
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 选择参考的课程改变时
 */
function onCourseChange(e: any) {
  tableRuleLoading.value = true;
  getRuleByCourseId(e)
    .then(({ data }) => {
      templateRules.value = data;
    })
    .finally(() => {
      tableRuleLoading.value = false;
    });
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function openEditDialog(
  parentId?: number,
  ruleId?: number,
  type?: RuleTypeEnum
) {
  listRuleOptions((ruleId || parentId)!)
    .then(({ data }) => {
      ruleOptions.value = data;
    })
    .then(() => {
      editRuleDialog.visible = true;
      if (ruleId) {
        editRuleDialog.title = "编辑规则";
        getRuleForm(ruleId).then(({ data }) => {
          Object.assign(editRuleFormData, data);
          ruleCacheData.type = data.type;
          ruleCacheData.grades = data.grades ?? undefined;
        });
      } else {
        editRuleDialog.title = "新增规则";
        editRuleFormData.parentId = parentId;
        if (type == RuleTypeEnum.CALLED) {
          editRuleFormData.type = RuleTypeEnum.BRANCH;
        } else {
          editRuleFormData.type = RuleTypeEnum.RULE;
        }
      }
    });
}

/**
 * 删除规则
 */
function handleDelete(id?: number) {
  const ruleIds = [id || ids.value].join(",");
  if (!ruleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除规则?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteRules(ruleIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 规则类型 change
 */
function onRuleTypeChange() {
  // 如果菜单类型改变，清空规则成绩；未改变在切换后还原规则成绩
  if (editRuleFormData.type !== ruleCacheData.type) {
    editRuleFormData.grades = undefined;
  } else {
    editRuleFormData.grades = ruleCacheData.grades;
  }
}

/**
 * 规则模板类型 change
 */
function onTemplateChange(e: any) {
  // 如果菜单类型改变，清空规则成绩；未改变在切换后还原规则成绩
  if (e == 1) {
    tableRuleLoading.value = true;
    getTemplateRules()
      .then(({ data }) => {
        templateRules.value = data;
      })
      .finally(() => {
        tableRuleLoading.value = false;
      });
  } else if (e == 2) {
    templateRules.value = [];
    getCourseOptions(courseId.value).then(({ data }) => {
      courseOptions.value = data;

      // templateRules.value = data;
    });
  }
}

/**
 * 下面是弹窗组件
 */
/**
 * 打开添加规则弹窗
 */
async function openDialog() {
  dialog.visible = true;
  dialog.title = "编辑评阅规则";
}

/**
 * 下面是弹窗组件
 */
/**
 * 打开添加规则弹窗
 */
async function openAddDialog() {
  addDialog.visible = true;
  addDialog.title = "添加评阅规则模板";
  if (templateType.value == "1") {
    tableRuleLoading.value = true;
    getTemplateRules()
      .then(({ data }) => {
        templateRules.value = data;
      })
      .finally(() => {
        tableRuleLoading.value = false;
      });
  } else if (templateType.value == "2") {
    templateRules.value = [];
    getCourseOptions(courseId.value).then(({ data }) => {
      courseOptions.value = data;

      // templateRules.value = data;
    });
  }
}
/**
 * 创建关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
}

/**
 * 创建关闭弹窗
 */
function closeAddDialog() {
  addDialog.visible = false;
}

/**
 * 创建关闭弹窗
 */
function closeEditRuleDialog() {
  editRuleDialog.visible = false;
}

/**
 * 规则保存提交
 */
function submitEditForm() {
  editFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const ruleId = editRuleFormData.id;
      if (ruleId) {
        updateRule(ruleId, editRuleFormData).then(() => {
          ElMessage.success("修改成功");
          editFormRef.value.resetFields();
          closeEditRuleDialog();
          ruleListInfo(ruleIdCache.value).then(({ data }) => {
            ruleListOf.value = data;
          });
        });
      } else {
        addRule(editRuleFormData).then(() => {
          ElMessage.success("新增成功");
          editFormRef.value.resetFields();
          closeEditRuleDialog();
          ruleListInfo(ruleIdCache.value).then(({ data }) => {
            ruleListOf.value = data;
          });
        });
      }
    }
  });
}

/**
 * 新增规则保存提交
 */
function submitAddForm() {
  addFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      addCustomRule(addFormData, courseId.value).then(() => {
        ElMessage.success("新增成功");
        addFormRef.value.resetFields();
        closeAddDialog();
        handleQuery();
      });
    }
  });
}

/**
 * 删除挥着
 * @param ruleId 菜单ID
 */
function handleRuleDelete(ruleId: number) {
  if (!ruleId) {
    ElMessage.warning("请选择删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteRule(ruleId).then(() => {
        ElMessage.success("删除成功");
        handleQuery();
        ruleListInfo(ruleIdCache.value).then(({ data }) => {
          ruleListOf.value = data;
        });
      });
    })
    .catch(() => ElMessage.info("已取消删除"));
}

onMounted(() => {
  courseId.value = courseStore.courseId;
  handleQuery(); // 初始化用户列表数据
  appStore.sidebar.opened = false;
});
</script>

<style scoped></style>
